package com.bluefish.bltuan.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bluefish.bltuan.dao.SubscriberDao;
import com.bluefish.bltuan.module.Category;
import com.bluefish.bltuan.module.mail.Subscriber;
import com.bluefish.bltuan.service.SubscriberService;
import com.bluefish.bltuan.util.PageIndex;

@Service
@Transactional
public class SubscriberServiceImpl implements SubscriberService {

	private SubscriberDao subscriberDao;
	
	private Subscriber findByEmail(String email){
		List<Subscriber> subscribers = this.subscriberDao.findByEmail(email);
		return subscribers != null && subscribers.size() > 0 ?
				subscribers.get(0) : null;
	}
	
	public boolean subscribe(String email, Category city) {
		Subscriber subscriber = findByEmail(email); 
		Subscriber temp = new Subscriber(email, city);
		if(subscriber == null || !subscriber.equals(temp)){
			this.subscriberDao.save(temp);
			return true;
		}
		return false;
	}

	public boolean unSubscribe(String email) {
		Subscriber subscriber = findByEmail(email); 
		if(subscriber != null){
			this.subscriberDao.delete(subscriber);
			return true;
		}
		return false;
	}
	
	public List<Subscriber> listAll() {
		return this.subscriberDao.list();
	}

	public void delete(Subscriber t) {
		this.subscriberDao.delete(t);
	}

	public Subscriber findById(Integer id) {
		return this.subscriberDao.findById(id);
	}

	public void save(Subscriber t) {
		this.subscriberDao.save(t);
	}

	public void update(Subscriber t) {
		this.subscriberDao.update(t);
	}
	
	public void setSubscriberDao(SubscriberDao subscriberDao) {
		this.subscriberDao = subscriberDao;
	}

	public List<Subscriber> list(PageIndex pageIndex) {
		return this.subscriberDao.list(pageIndex);
	}

}
